<template>
  <div class="menu-manage-wrapper">
    <div class="first-menus">
      <el-card class="box-card">
        <div class="card-header-box" slot="header">
          <span class="box-card-title">菜单管理</span>
          <div class="header-operate">
            <el-button size="mini" type="primary" icon="el-icon-plus" @click="showModal($event,'add')">
              <span>新增一级节点</span>
            </el-button>
            <el-button size="mini" type="primary" icon="el-icon-delete" @click="deleteNode()">
              <span>删除节点</span>
            </el-button>
          </div>
        </div>
        <tree-view ref="first" :treeData="generateTree" :expandOnClickNode="false" :showCheckbox="true" :defaultExpandAll="true" :showFlag="showFlag"
                   :operateLevel="operateLevel" @on-add="showModal($event,'add')" @on-edit="showModal($event,'edit')"
                   @on-delete="showModal($event,'delete')" @on-check-change="firstCheckChange">
        </tree-view>
      </el-card>
    </div>
    <el-dialog :title="menuDialogTitle" width="600px" :visible.sync="generateFirstMenu">
      <div v-if="menuDialogTitle !== '删除菜单'">
        <input-list-view :items="dialogItems" labelWidth="140px" width="500px"></input-list-view>
      </div>
      <div v-else>
        您确定要删除这些菜单吗？
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveFirstMenu">确 定</el-button>
        <el-button @click="generateFirstMenu = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  export default {
    name: 'MenuManage',
    data() {
      let baseUrl = managerRemoteUrl;
      return {
        urls: {
          getMenuUrl: baseUrl + '/menu', //获取右侧所有的菜单树
          getMenuHeaderUrl: "./static/json/menu-manage.json",//获取新增和编辑时的字段
          getUserRoleUrl: baseUrl + "/combobox/role", //用户角色
          getOprationUrl: baseUrl + "/combobox/opration", //权限标识
          addMenuUrl: baseUrl + "/menu/node", //新增菜单
          deleteNodeUrl: baseUrl + '/menu/node/del', //批量删除菜单
        },
        generateTree: [],
        selectedFirstMenus: [],
        generateFirstMenu: false,
        menuDialogTitle: '',
        deleteFlag: false,
        showFlag:{
          isAddShow: true,
          isEditShow: true,
          isDeleteShow: true
        },
        operateLevel:{
          add:[1,2,3],
          edit:[1,2,3],
          delete:[2,3]
        },
        cols:[],
        dialogItems:[],
        currentNode:null
      }
    },
    mounted() {
      this.getMenuData();
      this.getInitData();
    },
    methods: {
      //获取菜单树
      getMenuData() {
        let me = this;
        this.generateTree = [];
        this.httpRequest('get',`${this.urls.getMenuUrl}`,{},{
          fullSuccess: true
        }).then(res => {
          if (res.value.children && res.value.children.length != 0) {
            me.generateTree = res.value.children;
          }
        })
      },
      //获取新增和编辑时的字段
      getMenuHeader(){
        return new Promise((resolve, reject) => {
          this.httpRequest('get', `${this.urls.getMenuHeaderUrl}`, {}, {
            fullSuccess: true
          }).then(res => {
            this.cols = res.cols;
            resolve(res)
          })
        })
      },
      //获取全部角色
      getUserRole() {
        return new Promise((resolve, reject) => {
          this.httpRequest("get", this.urls.getUserRoleUrl, {}, {
            fullSuccess: true
          }).then(res => {
            resolve(res.value)
          })
        })
      },
      //获取权限标识
      getOpration() {
        return new Promise((resolve, reject) => {
          this.httpRequest("get", this.urls.getOprationUrl, {}, {
            fullSuccess: true
          }).then(res => {
            resolve(res.value)
          })
        })
      },
      getInitData() {
        Promise.all([this.getMenuHeader(), this.getUserRole(),this.getOpration()]).then(res => {
          this.cols.forEach(d => {
            if (d.field === "roleIds") {
              d.option = res[1];
            }else if(d.field === "oprationIds"){
              d.option = res[2];
            }
          });
        })
      },
      showModal(e,str) {
        this.currentNode = e ? e.node : undefined;
        if (str === 'add') {
          if (this.currentNode === undefined) {
            this.menuDialogTitle = '新增一级菜单';
          } else {
            this.menuDialogTitle = '新增菜单';
          }
          this.dialogItems = this.cloneObj(this.getModalDefaultInfo(this.cols,"addable",this));
        }else if(str === 'edit'){
          this.menuDialogTitle = "编辑菜单";
          let info = this.cloneObj(this.getModalDefaultInfo(this.cols,"editable",this));
          this.dialogItems = info.map(d => {
            let obj = this.cloneObj(d);
            obj["value"] = this.currentNode.data.data[d.field];
            return obj;
          });
        } else if (str === 'delete') {
          this.deleteFlag = true;
          this.menuDialogTitle = "删除菜单";
        }
        this.generateFirstMenu = true;
      },
      //保存节点
      saveFirstMenu() {
        if(this.menuDialogTitle === "删除菜单"){
          this.deleteNodeSave();
        }else{
          let param = {}, canRequest = true;
          let str = this.checkRequire(this.dialogItems); //检查必填项是否是空项
          if (!this.isEmpty(str)) {
            this.message(this, "warn", str, true);
            canRequest = false;
            return;
          } else {
            canRequest = true;
          }
          this.dialogItems.forEach(d => {
            if (!this.isEmpty(d.value)) {
              if (this.checkReg(d.value, d.label)) {
                param[d.id] = d.value;
              } else {
                str += d.label + "的格式不正确，请更改后再保存<br/>";
                canRequest = false;
              }
            }
          });
          if (!canRequest) {
            this.message(this, "warn", str, true);
            return;
          }
          if(this.menuDialogTitle === "编辑菜单"){
            param["menuId"] = this.currentNode.data.data["menuId"];
            param["menuPid"] = this.currentNode.data.data["menuPid"];
            this.save('put',param);
          }else{
            param["menuPid"] = this.currentNode ? this.currentNode.key : null;
            this.save('post',param);
          }
        }
      },
      save(type,param){
        let url = this.urls.addMenuUrl;
        this.httpRequest(type,url,param,{
          fullSuccess: true
        }).then(res => {
          this.message(this,'success',res.message);
          this.getMenuData();
          this.generateFirstMenu = false;
        })
      },
      //删除节点
      deleteNodeSave() {
        let me = this, ids = [];
        if (this.deleteFlag) {
          ids = [this.currentNode.key];
        } else {
          this.selectedFirstMenus.forEach((d) => {
            ids.push(d.id);
          });
        }
        this.httpRequest('post',this.urls.deleteNodeUrl,ids,{
          fullSuccess: true
        }).then(res => {
          this.message(this,'success',res.message);
          me.getMenuData();
          me.deleteFlag = false;
          me.selectedFirstMenus = [];
          me.generateFirstMenu = false;
        })
      },
      //删除一级节点
      deleteNode() {
        if (this.selectedFirstMenus && this.selectedFirstMenus.length === 0) {
          this.$notify({title: '警告', message: '请先选择需要删除的菜单', type: 'warning'});
          return false;
        }
        this.deleteFlag = false;
        this.menuDialogTitle = "删除菜单";
        this.generateFirstMenu = true;
      },
      //树节点被选中
      firstCheckChange(data, isChecked, children) {
        this.selectedFirstMenus = this.$refs.first.$refs.tree.getCheckedNodes();
      },
    }
  }
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
  @import "../../../assets/styles/base_style";
  .menu-manage-wrapper:after {
    @include clearFloat;
  }
  .menu-manage-wrapper {
    // @include minHeightInherit;
    width: 100%;
    height: 100%;
    .menu-manage-header {
      padding-bottom: 10px;
    }
    .card-header-box{
      position: relative;
      .header-operate{
        position: absolute;
        right: 0;
        top: -4px;
      }
      @include mediaScreen(xs) {
        .header-operate {
          span{
            display: none;
          }
        }
      }
    }
    .box-card-title {
      font-size: 16px;
      color: $fontColor333;
      font-weight: bold;
    }
    .first-menus {
      float: left;
      width: calc(100%);
      height: calc(100% - 45px);
      .box-card {
        height: 100%;
      }
    }
  }
</style>
<style rel="stylesheet/scss" lang="scss">
  @import "../../../assets/styles/base_style";
  .menu-manage-wrapper {
    .el-card__body {
      height: calc(100% - 50px);
      padding: 0;
    }
    .el-card__header {
      background: #EFF3FE;
      border: 1px solid #e1e1e1;
      height: 52px;
      padding: 15px 20px;
      position: relative;
    }
  }
</style>
